package sz.szsmk.citizencard.ui.activity;

import android.content.Context;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.chenenyu.router.annotation.Route;
import com.google.gson.Gson;
import com.gyf.immersionbar.ImmersionBar;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.BusSearchHistoryActivityBinding;
import sz.szsmk.citizencard.db.BusSiteDb;
import sz.szsmk.citizencard.db.BusSiteDbDao;
import sz.szsmk.citizencard.db.PublicDb;
import sz.szsmk.citizencard.db.PublicDbDao;
import sz.szsmk.citizencard.db.StationChangeDb;
import sz.szsmk.citizencard.db.StationChangeDbDao;
import sz.szsmk.citizencard.dialog.TwoButtonDialog;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.response.PublicBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryBusLineNearbyRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryNearStandbyRes;
import sz.szsmk.citizencard.model.network.bean.response.SearchBean;
import sz.szsmk.citizencard.model.network.bean.response.TransBean;
import sz.szsmk.citizencard.mvp.contract.IBusHistoryContact;
import sz.szsmk.citizencard.mvp.presenter.BusHistoryPresenter;
import sz.szsmk.citizencard.ui.adapter.HistoryAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.MesageEventBus;
import sz.szsmk.citizencard.widget.SwipeItemLayout;

/**
 * Copyright (c)2019
 * author: zdh
 * created on: 2019/1/14 17:02
 * description:
 */
@Route("BusSearchHistotyActivity")
public class BusSearchHistotyActivity extends IBaseActivity<BusHistoryPresenter, BusSearchHistoryActivityBinding>
        implements View.OnClickListener, IBusHistoryContact.IBusHistoryView, OnGetPoiSearchResultListener {
    public static BusSearchHistotyActivity instance;

    EditText searchEt;
    ImageView back;
    TextView settingTitle;
    LinearLayout search_del;
    RecyclerView busSearchHistoryRv;
    TextView cancelTv;
    ImageView cancelIv;
    //    private SearchHistoryDao historyDao;
    private ArrayList<String> mList = new ArrayList<>();
    private ArrayList<String> dataList = new ArrayList<>();
    private ArrayList<String> realList = new ArrayList<>();
    private ArrayList<PublicBean.PublicListBean> mPublicList = new ArrayList<>();
    private HistoryAdapter historyAdapter;
    private StationChangeDbDao stationChangeDbDao;
    private String type;
    private PublicDbDao publicDbDao;
    private BusSiteDbDao busSiteDbDao;
    private PoiSearch mPoiSearch = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.bus_search_history_activity;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent())
                .build().inject(this);
    }

    @Override
    protected void initViews() {
        ImmersionBar.with(this)
                .fitsSystemWindows(true)
                .statusBarDarkFont(true, 0f)
                .statusBarColor(R.color.white).init();
        instance = this;
        type = getIntent().getStringExtra(Constant.TYPE);
        stationChangeDbDao = DaggerApplication.getmDaoSession().getStationChangeDbDao();
        publicDbDao = DaggerApplication.getmDaoSession().getPublicDbDao();
        busSiteDbDao = DaggerApplication.getmDaoSession().getBusSiteDbDao();


        searchEt = dataBinding.searchEt;
        back = findViewById(R.id.back);

        settingTitle = findViewById(R.id.setting_title);

        search_del = findViewById(R.id.search_del);

        busSearchHistoryRv = findViewById(R.id.bus_search_history_rv);

        cancelTv = findViewById(R.id.cancel_tv);

        cancelIv = findViewById(R.id.cancel_iv);




        back.setOnClickListener(this);
        dataBinding.cancelIv.setOnClickListener(this);
        settingTitle.setText("站点/线路搜索");
        dataBinding.cancelIv.setVisibility(View.GONE);
        if (type.equals("line")) {
            searchEt.setHint("请输入线路名称");
        }
        if (type.equals("site")) {
            searchEt.setHint("请输入站点名称");
        }
        cancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        cancelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchEt.setText("");
            }
        });
        searchEt.addTextChangedListener(editclick);
        searchEt.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {

                        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);


                }
                return false;
            }
        });
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        busSearchHistoryRv.setLayoutManager(linearLayoutManager);
        busSearchHistoryRv.addOnItemTouchListener(new SwipeItemLayout.OnSwipeItemTouchListener(getApplicationContext()));
        historyAdapter = new HistoryAdapter(this);
        historyAdapter.GhfOnClick(new HistoryAdapter.GhfInterface() {
            @Override
            public void onClick(View view, String name, String guide, String json, int position) {

                Bundle bundle = new Bundle();
                if ("line".equals(type)) {
                    bundle.putString("line_guid", guide);
                    bundle.putString("line_name", name);
                    PublicDb publicDb = new PublicDb();
                    publicDb.setLinename(name);
                    publicDb.setLineguid(guide);
                    publicDb.setLinedirection(json);
                    publicDbDao.insert(publicDb);
                    JumpUtils.jumptoNatvie(BusSearchHistotyActivity.this, "RealTimeLineActivity", 0, bundle);
                }
                if ("site".equals(type)) {
                    bundle.putString("stand_name", name);
                    bundle.putString("stand_guid", guide);

                    BusSiteDb busSiteDb = new BusSiteDb();
                    busSiteDb.setLineguid(guide);
                    busSiteDb.setLinename(name);
                    busSiteDbDao.insert(busSiteDb);
                    JumpUtils.jumptoNatvie(BusSearchHistotyActivity.this, "BusSiteDetailActivity", 0, bundle);
                }
                if (type!=null && type.equals("transstart")){

                    StationChangeDb  stationChangeDb = new StationChangeDb();
                    stationChangeDb.setStationname(mPublicList.get(position).getLine_name());
                    stationChangeDb.setStationLat(mPublicList.get(position).getLatitude());
                    stationChangeDb.setStationlong(mPublicList.get(position).getLongitude());
                    stationChangeDbDao.insert(stationChangeDb);
                    MesageEventBus mesageEventBus = new MesageEventBus();
                    if("transstart".equals(type)){
                        mesageEventBus.setStart(mPublicList.get(position).getLine_name());
                        mesageEventBus.setEnd("");
                    }

//                mesageEventBus.setStart(mStringList.get(position));
                    mesageEventBus.setLat(mPublicList.get(position).getLatitude());
                    mesageEventBus.setLog(mPublicList.get(position).getLongitude());
                    EventBus.getDefault().postSticky(mesageEventBus);



                    finish();
                } else  if (type!=null && type.equals("transend")){

                    StationChangeDb  stationChangeDb = new StationChangeDb();
                    stationChangeDb.setStationname(mPublicList.get(position).getLine_name());
                    stationChangeDb.setStationLat(mPublicList.get(position).getLatitude());
                    stationChangeDb.setStationlong(mPublicList.get(position).getLongitude());
                    stationChangeDbDao.insert(stationChangeDb);
                    MesageEventBus mesageEventBus = new MesageEventBus();
                    if("transend".equals(type)){
                        mesageEventBus.setStart("");
                        mesageEventBus.setEnd(mPublicList.get(position).getLine_name());
                    }
                    mesageEventBus.setLat(mPublicList.get(position).getLatitude());
                    mesageEventBus.setLog(mPublicList.get(position).getLongitude());
                    EventBus.getDefault().postSticky(mesageEventBus);



                    finish();
                }
            }
        });
        historyAdapter.setOnDelListener(new HistoryAdapter.OnDelListener() {
            @Override
            public void onDel(int position) {
                showSignlDelDialog(position);
            }
        });
        busSearchHistoryRv.setAdapter(historyAdapter);
        search_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAllDelDialog();
            }
        });
    }

    private TextWatcher editclick = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String inputKey = searchEt.getText().toString();
            if (inputKey.length() > 0) {
                if (type.equals("line")) {
                    mPresenter.queryLineByLineName(inputKey);
                }
                if (type.equals("site")) {
                    mPresenter.queryBusStandByKey(inputKey);
                }
                if(type.equals("transstart")||type.equals("transend")){
                    mPoiSearch = PoiSearch.newInstance();
                    mPoiSearch.setOnGetPoiSearchResultListener(BusSearchHistotyActivity.this);

                    mPoiSearch.searchInCity((new PoiCitySearchOption())
                            .city("苏州").keyword(inputKey).pageNum(0));

                }
                dataBinding.searchRl.setVisibility(View.GONE);
                dataBinding.cancelIv.setVisibility(View.VISIBLE);
            } else {
                dataBinding.searchRl.setVisibility(View.VISIBLE);
                historyAdapter.setViewData(dataList);
                historyAdapter.notifyDataSetChanged();
                dataBinding.cancelIv.setVisibility(View.GONE);
            }
        }
    };

    public boolean HasDigit(String content) {
        boolean flag = false;
        Pattern p = Pattern.compile(".*\\d+.*");
        Matcher m = p.matcher(content);
        if (m.matches()) {
            flag = true;
        }
        return flag;
    }


    @Override
    protected void updateViews() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back) {
            finish();
        } else if (id == R.id.cancel_iv) {
            dataBinding.searchRl.setVisibility(View.VISIBLE);
            historyAdapter.setViewData(dataList);
            dataBinding.searchEt.setText("");
            dataBinding.cancelIv.setVisibility(View.GONE);
            historyAdapter.notifyDataSetChanged();
        }
    }

    private void showSignlDelDialog(final int position) {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "确认删除本条记录吗");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                String name = mPublicList.get(position).getLine_name();
//                Note note = new Note(null, name);
                if ("line".equals(type)) {
                    List<PublicDb> notelist = publicDbDao.queryBuilder().where(PublicDbDao.Properties.Linename.eq(name)).list();
                    for (PublicDb note : notelist) {
                        publicDbDao.delete(note);
                    }
                }
                else if("site".equals(type)){
                    List<BusSiteDb> notelist = busSiteDbDao.queryBuilder().where(BusSiteDbDao.Properties.Linename.eq(name)).list();
                    for (BusSiteDb note : notelist) {
                        busSiteDbDao.delete(note);
                    }
                }else {
                    List<StationChangeDb> notelist = stationChangeDbDao.queryBuilder().where(StationChangeDbDao.Properties.Stationname.eq(name)).list();
                    for (StationChangeDb note : notelist) {
                        stationChangeDbDao.delete(note);
                    }
                }
                Iterator<PublicBean.PublicListBean> it = mPublicList.iterator();
                while (it.hasNext()) {
                    PublicBean.PublicListBean tempitem = it.next();
                    if (tempitem.getLine_name().equals(name)) {
                        it.remove();
                    }
                }

                historyAdapter.setPublicData(mPublicList,type);
                historyAdapter.notifyDataSetChanged();
                dialog.cancel();



            }
        });
        dialog.show();
    }

    private void showAllDelDialog() {
        final TwoButtonDialog dialog = new TwoButtonDialog(this, "确认删除全部记录吗");
        dialog.setOnOkClickListener(new TwoButtonDialog.OnOkClickListener() {
            @Override
            public void onOkClick() {

                dialog.cancel();
            }
        });
        dialog.setOnCancelClickListener(new TwoButtonDialog.OnCancelClickListener() {
            @Override
            public void onCancelClick() {
                if ("line".equals(type)) {
                    publicDbDao.deleteAll();
                }
                if ("site".equals(type)) {
                    busSiteDbDao.deleteAll();
                }
//                dataList.clear();
                mPublicList.clear();
                historyAdapter.setPublicData(mPublicList, type);
                historyAdapter.notifyDataSetChanged();
                dialog.cancel();
            }
        });
        dialog.show();
    }

    @Override
    protected void onResume() {
        super.onResume();

        mList.clear();
        dataList.clear();
        mPublicList.clear();
        if ("line".equals(type)) {
            List<PublicDb> publicDbs = publicDbDao.loadAll();
            if (publicDbs != null) {
                for (int i = 0; i < publicDbs.size(); i++) {
                    PublicDb publicDb = publicDbs.get(i);
                    PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
                    publicListBean.setLine_name(publicDb.getLinename());
                    publicListBean.setLine_guid(publicDb.getLineguid());
                    publicListBean.setLine_direction(publicDb.getLinedirection());
                    mPublicList.add(publicListBean);
                }
            }
            for (int i = 0; i < mPublicList.size() - 1; i++) {
                for (int j = mPublicList.size() - 1; j > i; j--) {
                    if (mPublicList.get(j).getLine_guid().equals(mPublicList.get(i).getLine_guid())) {
                        mPublicList.remove(j);
                    }
                }
            }
        }
        if ("site".equals(type)) {
            List<BusSiteDb> busSiteDbs = busSiteDbDao.loadAll();
            if (busSiteDbs != null) {
                for (int i = 0; i < busSiteDbs.size(); i++) {
                    BusSiteDb busSiteDb = busSiteDbs.get(i);
                    PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
                    publicListBean.setLine_name(busSiteDb.getLinename());
                    publicListBean.setLine_guid(busSiteDb.getLineguid());
                    publicListBean.setLine_direction(busSiteDb.getLinedirection());
                    mPublicList.add(publicListBean);
                }
            }
            for (int i = 0; i < mPublicList.size() - 1; i++) {
                for (int j = mPublicList.size() - 1; j > i; j--) {
                    if (mPublicList.get(j).getLine_name().equals(mPublicList.get(i).getLine_name())) {
                        mPublicList.remove(j);
                    }
                }
            }
        }
        if ("transstart".equals(type)||"transend".equals(type)) {
            List<StationChangeDb> busSiteDbs = stationChangeDbDao.loadAll();
            if (busSiteDbs != null) {
                for (int i = 0; i < busSiteDbs.size(); i++) {
                    StationChangeDb busSiteDb = busSiteDbs.get(i);
                    PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
                    publicListBean.setLine_name(busSiteDb.getStationname());
                    publicListBean.setLatitude(busSiteDb.getStationLat());
                    publicListBean.setLongitude(busSiteDb.getStationlong());
                    mPublicList.add(publicListBean);
                }
            }
            for (int i = 0; i < mPublicList.size() - 1; i++) {
                for (int j = mPublicList.size() - 1; j > i; j--) {
                    if (mPublicList.get(j).getLine_name().equals(mPublicList.get(i).getLine_name())) {
                        mPublicList.remove(j);
                    }
                }
            }
        }
        historyAdapter.setPublicData(mPublicList, type);
        historyAdapter.notifyDataSetChanged();
    }


    public static ArrayList<String> removeDuplicate(ArrayList<String> list) {
        for (int i = 0; i < list.size() - 1; i++) {
            for (int j = list.size() - 1; j > i; j--) {
                if (list.get(j).equals(list.get(i))) {
                    list.remove(j);
                }
            }
        }
        return list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void queryBusStandByKeySucc(QueryNearStandbyRes response) {
        List<QueryNearStandbyRes.BusSiteListBean> busSiteList = response.getBusSiteList();
        mPublicList.clear();

//        realList.clear();
        for (int i = 0; i < busSiteList.size(); i++) {
            PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
            publicListBean.setLine_guid(busSiteList.get(i).getStand_guid());
            publicListBean.setLine_direction("");
            publicListBean.setLine_name(busSiteList.get(i).getStand_name());
            mPublicList.add(publicListBean);
        }
        historyAdapter.setPublicData(mPublicList, type);
        historyAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryBusStandByKeyFail(QueryNearStandbyRes response) {
        Toast.makeText(instance, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void queryLineByLineNameSucc(QueryBusLineNearbyRes response) {

        List<QueryBusLineNearbyRes.BusLineListBean> busLineList = response.getBusLineList();

        mPublicList.clear();
        realList.clear();
        for (int i = 0; i < busLineList.size(); i++) {
            PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
            publicListBean.setLine_guid(busLineList.get(i).getLine_guid());
            publicListBean.setLine_direction(busLineList.get(i).getLine_direction());
            publicListBean.setLine_name(busLineList.get(i).getLine_name());
            publicListBean.setType(busLineList.get(i).getLine_type());
            mPublicList.add(publicListBean);
        }

        historyAdapter.setPublicData(mPublicList, type);
        historyAdapter.notifyDataSetChanged();
    }

    @Override
    public void queryLineByLineNameFail(QueryBusLineNearbyRes response) {
        Toast.makeText(instance, response.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(BusSearchHistotyActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }

        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            String json = new Gson().toJson(result);
            SearchBean searchBean = new Gson().fromJson(json, SearchBean.class);
            List<SearchBean.EBean> searchResult = searchBean.getE();
            TransBean transBean = new TransBean();
            mPublicList.clear();
//            realList.clear();
            for (int i = 0; i < searchResult.size(); i++) {
                SearchBean.EBean eBean = searchResult.get(i);
//                mStringList.add(eBean.getName());
//                double latitude = eBean.getLocation().getLatitude();
//                transBean.setLat(eBean.getLocation().getLatitude());
//                transBean.setLog(eBean.getLocation().getLongitude());
//                mBean.add(transBean);
                PublicBean.PublicListBean publicListBean = new PublicBean.PublicListBean();
//                publicListBean.setLine_guid(busLineList.get(i).getLine_guid());
//                publicListBean.setLine_direction(busLineList.get(i).getLine_direction());
                publicListBean.setLine_name(eBean.getName());
                publicListBean.setLongitude(eBean.getLocation().getLongitude());
                publicListBean.setLatitude(eBean.getLocation().getLatitude());
            //    publicListBean.setType(busLineList.get(i).getLine_type());
                mPublicList.add(publicListBean);
            }
            historyAdapter.setPublicData(mPublicList,type);
            historyAdapter.notifyDataSetChanged();
        }else {
            Toast.makeText(this, "未搜索到结果", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailSearchResult poiDetailSearchResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }
}
